import 'dart:io';

import 'package:geocoding/geocoding.dart';
import 'package:geolocator/geolocator.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:sptapp/widget/common_widget.dart';

class LocationService {
  static final LocationService _instance = LocationService._internal();
  factory LocationService() => _instance;
  LocationService._internal();

  Future<bool> _checkPermission() async {
    bool serviceEnabled;
    LocationPermission permission;

    // 检查位置服务是否启用
    serviceEnabled = await Geolocator.isLocationServiceEnabled();
    print('检查位置服务是否启用 $serviceEnabled');
    if (!serviceEnabled) {
      // 请求用户启用位置服务
      await Permission.location.request();
      serviceEnabled = await Geolocator.isLocationServiceEnabled();
      if (!serviceEnabled) {
        return false;
      }
    }

    // 检查位置权限
    permission = await Geolocator.checkPermission();
    print('检查位置权限 $permission');
    if (permission == LocationPermission.denied) {
      permission = await Geolocator.requestPermission();
      if (permission == LocationPermission.denied) {
        return false;
      }
    }

    if (permission == LocationPermission.deniedForever) {
      return false;
    }

    return true;
  }

  // 获取当前位置
  Future<Position?> getCurrentLocation() async {
    try {
      final hasPermission = await _checkPermission();
      if (!hasPermission) {
        return null;
      }
      print('hasPermission: $hasPermission');
      LocationSettings settings = LocationSettings(
        distanceFilter: 100,
        accuracy: LocationAccuracy.low,
        timeLimit: Duration(seconds: 10)
      );
      if(Platform.isIOS){
        settings = AppleSettings(accuracy: LocationAccuracy.low,distanceFilter: 100, timeLimit: Duration(seconds: 10));
      }else if(Platform.isAndroid){
        settings = AndroidSettings(
            forceLocationManager: true,
            distanceFilter: 100,
            accuracy: LocationAccuracy.low,
            timeLimit: Duration(seconds: 10)
        );
      }
      showLoading();
      Geolocator.getLastKnownPosition(forceAndroidLocationManager: true);
      Position p = await Geolocator.getCurrentPosition(locationSettings: settings);
      hideLoading();
      return p;
    } catch (e) {
      return null;
    }
  }

  // 监听位置变化
  Stream<Position> getLocationStream() {
    return Geolocator.getPositionStream(
      locationSettings: const LocationSettings(
        accuracy: LocationAccuracy.medium,
        distanceFilter: 100, // 最小更新距离（米）
        timeLimit: Duration(seconds: 10)
      ),
    );
  }

  // 计算两点之间的距离（米）
  double calculateDistance(
      double startLatitude,
      double startLongitude,
      double endLatitude,
      double endLongitude,
      ) {
    return Geolocator.distanceBetween(
      startLatitude,
      startLongitude,
      endLatitude,
      endLongitude,
    );
  }
}

class GeocodingService {
  static final GeocodingService _instance = GeocodingService._internal();
  factory GeocodingService() => _instance;
  GeocodingService._internal();

  // 根据经纬度获取地址信息
  Future<String> getAddressFromLatLng(double latitude, double longitude) async {
    setLocaleIdentifier("en_US");
    try {
      final placemarks = await placemarkFromCoordinates(latitude, longitude);
      if (placemarks.isEmpty) return '';

      final place = placemarks.first;
      return _formatAddress(place);
    } catch (e) {
      return '';
    }
  }

  // 根据地址获取经纬度
  Future<Location?> getLatLngFromAddress(String address) async {
    try {
      final locations = await locationFromAddress(address);
      return locations.isNotEmpty ? locations.first : null;
    } catch (e) {
      print('获取坐标失败: $e');
      return null;
    }
  }

  // 格式化地址信息
  String _formatAddress(Placemark place) {
    final components = <String>[];

    if (place.country?.isNotEmpty == true) {
      components.add(place.country!);
    }
    if (place.administrativeArea?.isNotEmpty == true) {
      components.add(place.administrativeArea!);
    }
    if (place.locality?.isNotEmpty == true) {
      components.add(place.locality!);
    }
    if (place.subLocality?.isNotEmpty == true) {
      components.add(place.subLocality!);
    }
    if (place.thoroughfare?.isNotEmpty == true) {
      components.add(place.thoroughfare!);
    }
    if (place.subThoroughfare?.isNotEmpty == true) {
      components.add(place.subThoroughfare!);
    }

    return components.join(', ');
  }

  // 获取详细地址信息
  Future<Map<String, String>> getDetailedAddress(double latitude, double longitude) async {
    try {
      final placemarks = await placemarkFromCoordinates(latitude, longitude);
      if (placemarks.isEmpty) {
        return {'error': '未找到地址信息'};
      }

      final place = placemarks.first;
      return {
        'country': place.country ?? '',
        'administrativeArea': place.administrativeArea ?? '',
        'locality': place.locality ?? '',
        'subLocality': place.subLocality ?? '',
        'thoroughfare': place.thoroughfare ?? '',
        'subThoroughfare': place.subThoroughfare ?? '',
        'postalCode': place.postalCode ?? '',
        'name': place.name ?? '',
        'formatted': _formatAddress(place),
      };
    } catch (e) {
      return {'error': e.toString()};
    }
  }
}